package net.solvetheriddle.wwclient.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.solvetheriddle.wwclient.R;
import net.solvetheriddle.wwclient.WWLogic;
import net.solvetheriddle.wwclient.WWParser;
import net.solvetheriddle.wwclient.database.WWDatabaseManager;
import net.solvetheriddle.wwclient.entity.Project;
import net.solvetheriddle.wwclient.entity.Work;
import net.solvetheriddle.wwclient.view.ProjectNameVerticalTextView;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.FrameLayout;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class WorkOverviewActivity extends Activity {

  public static final int TIME_AXIS_TEXT_ROTATION_Y = 25;
  public static final int PROJECT_NAME_ROTATION_Y = 50;
  public static final int PROJECT_NAME_DP_LENGHT = 500; // possible: 100-1100
  private static final int PROJECT_NAME_Y_CORD = 10;
  private static final int PROJECT_NAME_X_CORD = 10;
  private static final int FIRST_COLUMN = 0;
  private static final int SECOND_COLUMN = 1;
  private static final int THIRD_COLUMN = 2;
  private static final int WORK_TIME_OFFSET = 0; //3600000;
  // timeLine measures and positions
  private static final int TIME_LINE_WIDTH = 272;
  private static final int TIME_LINE_HEIGHT = 2;
  private static final int TIME_LINE_LEFT_OFFSET = 5;
  private static final int TIME_LINE_TOP_OFFSET = 3;

  private List<AbsoluteLayout> cells;
  private List<Project> projects;

  private AbsoluteLayout cell1;
  private AbsoluteLayout cell2;
  private AbsoluteLayout cell3;
  private AbsoluteLayout scrollInside;
  private View timeLine;

  private WWDatabaseManager db;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.worklist);

    db = new WWDatabaseManager(getApplicationContext());

    setupCells();
    createTimeLine();

  }

  @Override
  protected void onResume() {
    super.onResume();
    updateTimeLine();
    deleteProjectsFromColumns();

    deactivateAllColumns();
    loadProjects();
    loadProjectsToColumns();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  /**
     * 
     */
  private void setupCells() {
    cell1 = (AbsoluteLayout) findViewById(R.id.cell1);
    cell2 = (AbsoluteLayout) findViewById(R.id.cell2);
    cell3 = (AbsoluteLayout) findViewById(R.id.cell3);
    cells = new ArrayList<AbsoluteLayout>();
    cells.add(cell1);
    cells.add(cell2);
    cells.add(cell3);
  }

  /**
   * Initializes and adds the time line to the UI.
   */
  private void createTimeLine() {
    scrollInside = (AbsoluteLayout) findViewById(R.id.scroll_inside);
    // Inicializing TimeLine
    timeLine = new View(this);
    timeLine.setBackgroundResource(R.color.time_line_red);
    timeLine.setLayoutParams(new AbsoluteLayout.LayoutParams(dpToPixels(TIME_LINE_WIDTH), dpToPixels(TIME_LINE_HEIGHT), dpToPixels(TIME_LINE_LEFT_OFFSET),
        dpToPixels(TIME_LINE_TOP_OFFSET)));
    scrollInside.addView(timeLine);
  }

  /**
   * Updates time line according to the current time.
   */
  private void updateTimeLine() {
    int position = getPositionFromMillis(WWLogic.getCurrentMillis());
    if (WWLogic.workInProgress()) {
      timeLine.setBackgroundResource(R.color.time_line_green);
    } else {
      timeLine.setBackgroundResource(R.color.time_line_red);
    }
    placeTimeLine(position);
  }

  /**
   * Inject projects and their work to columns.
   */
  private void loadProjectsToColumns() {
    // drawing projects
    if (!projects.isEmpty()) {
      for (int i = 0; i < projects.size() && i < 3; i++) {
        Project project = projects.get(i);
        int columnId = 2 - i;
        placeProjectAtColumn(project, columnId);
        if (project.isActive()) {
          getColumnById(columnId).setBackgroundResource(R.drawable.bubble_active);
        } else {
          getColumnById(columnId).setBackgroundResource(R.drawable.bubble_inactive);
        }
      }
      // } else if (projects.size() > 3) {
      // Toast.makeText(getApplicationContext(),
      // getString(R.string.tooManyProjects), Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(getApplicationContext(), getString(R.string.noProjects), Toast.LENGTH_LONG).show();
    }
  }

  /**
   * Loads current projects and their recent work from server.
   */
  private void loadProjects() {
    db.open();
    projects = db.getAllProjects();
    db.close();
  }

  /**
   * Returns position in graph
   * 
   * @param milis Number of milliseconds
   * @return position in graph
   */
  private int getPositionFromMillis(long millis) {
    Date date = new Date(millis);
    long millisFromLocalMidnight = 0;
    millisFromLocalMidnight += date.getHours();
    millisFromLocalMidnight *= 60;
    millisFromLocalMidnight += date.getMinutes();
    millisFromLocalMidnight *= 60;
    millisFromLocalMidnight += date.getSeconds();
    millisFromLocalMidnight *= 1000;
    
    
    int position = (int) (1200 * millisFromLocalMidnight / WWParser.ONE_DAY_IN_MILLIS);
    return position;
  }
  
  private int getLengthFromMillis(long millis) {
    int position = (int) (1200 * millis / WWParser.ONE_DAY_IN_MILLIS);
    return position;
  }

//  /**
//   * Returns position of time line in graph
//   * 
//   * @param milis Number of milliseconds
//   * @return position in graph
//   */
//  private int getTimelinePositionFromMilis(long millis) {
//    millis += TimeZone.getDefault().getRawOffset();
//    if (TimeZone.getDefault().useDaylightTime()) {
//      millis += TimeZone.getDefault().getDSTSavings();
//    }
//    if (millis > WWParser.ONE_DAY_IN_MILLIS) {
//      millis = millis % WWParser.ONE_DAY_IN_MILLIS;
//    }
//    int position = (int) (1200 * millis / WWParser.ONE_DAY_IN_MILLIS);
//    return position;
//  }

  /**
   * Places time line on selected position
   * 
   * @param position Position of time line in pixels
   */
  private void placeTimeLine(int position) {
    timeLine.setLayoutParams(new AbsoluteLayout.LayoutParams(dpToPixels(TIME_LINE_WIDTH), dpToPixels(TIME_LINE_HEIGHT), dpToPixels(TIME_LINE_LEFT_OFFSET), dpToPixels(position
        + TIME_LINE_TOP_OFFSET)));
  }

  /**
   * Places a bubble that represents a finished work to the bubble timer
   * 
   * @param position start position in pixels
   * @param height number of pixels corresponding to length of a work
   * @param column ID of column
   */
  private void placeBubbleAtColumn(int position, int height, int columnId) {
    // Create new Work
    View workBubble = new View(this);
    workBubble.setBackgroundResource(R.drawable.work_bubble);
    workBubble.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    if (height < 7) {
      height = 7;
    }
    FrameLayout workFrame = new FrameLayout(this);
    workFrame.addView(workBubble);
    // workFrame.setBackgroundDrawable(this.getResources().getDrawable(R.color.translucent_red));
    workFrame.setLayoutParams(new AbsoluteLayout.LayoutParams(LayoutParams.FILL_PARENT, dpToPixels(height), dpToPixels(0), dpToPixels(position)));
    workFrame.setPadding(dpToPixels(5), dpToPixels(2), dpToPixels(5), dpToPixels(2));

    getColumnById(columnId).addView(workFrame);
  }

  /**
   * @param columnId ID of a column
   * @return column of given ID
   */
  public AbsoluteLayout getColumnById(int columnId) {
    switch (columnId) {
    case FIRST_COLUMN:
      return cell1;
    case SECOND_COLUMN:
      return cell2;
    case THIRD_COLUMN:
      return cell3;
    }
    throw new IllegalArgumentException("ID out of range");
  }

  /**
   * Converts density points to display pixels.
   * 
   * @param dipper number of density points
   * @return number of pixels
   */
  public int dpToPixels(int dipper) {
    return ((int) (dipper * getResources().getDisplayMetrics().density));
  }

  /**
   * Fills the column with recent work on certain project and adds the name of
   * the project.
   * 
   * @param project Project of which the work is drawn into column
   * @param columnId Id of column in which the work should be drawn
   */
  private void placeProjectAtColumn(Project project, int columnId) {
    db.open();
    List<Work> worksOnProject = db.getTodayWorks(project.getId());
    db.close();

    for (Work work : worksOnProject) {
      long beginTime =  work.getFrom();
      long length;
      if( work.getTo() == 0) {
	// Unfinished work
	length = WWLogic.getCurrentMillis() - beginTime;
      } else {
	// Finished work
	length = work.getTo() - beginTime;
      }
      placeBubbleAtColumn(getPositionFromMillis(beginTime), getLengthFromMillis(length), columnId);
    }
    // Place project name label on column
    ProjectNameVerticalTextView projectName = new ProjectNameVerticalTextView(this);
    projectName.setLayoutParams(new AbsoluteLayout.LayoutParams(dpToPixels(PROJECT_NAME_DP_LENGHT), dpToPixels(PROJECT_NAME_DP_LENGHT), dpToPixels(PROJECT_NAME_X_CORD),
        dpToPixels(PROJECT_NAME_Y_CORD)));
    projectName.setTextAppearance(this, R.style.projectName);
    projectName.setText(project.getName());

    getColumnById(columnId).addView(projectName);
  }

  /**
   * Clears all columns.
   */
  private void deleteProjectsFromColumns() {
    cell1.removeAllViews();
    cell2.removeAllViews();
    cell3.removeAllViews();
  }

  /**
   * Sets all columns representing projects to inactive.
   */
  private void deactivateAllColumns() {
    cell1.setBackgroundResource(R.drawable.bubble_inactive);
    cell2.setBackgroundResource(R.drawable.bubble_inactive);
    cell3.setBackgroundResource(R.drawable.bubble_inactive);
  }

}
